package com.joker.product.init;

import com.joker.common.redis.service.RedisService;
import com.joker.product.domain.PmsSkuInfo;
import com.joker.product.service.IPmsSkuInfoService;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisWarmUpRunner implements ApplicationRunner {

    @Autowired
    private RedisService redisService;
    @Autowired
    private IPmsSkuInfoService pmsSkuInfoService;

    private static final String LOCK_KEY = "warm:up:lock";
    private static final long LOCK_EXPIRE_TIME = 30L;  // 锁的过期时间，单位秒

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 尝试获取分布式锁
        boolean locked = redisService.setCacheObjectIfAbsent(LOCK_KEY, "LOCKED", LOCK_EXPIRE_TIME, TimeUnit.SECONDS);
        
        if (!locked) {
            return;  // 如果获取锁失败，直接返回
        }

        try {
            List<PmsSkuInfo> pmsSkuInfos = pmsSkuInfoService.selectSkuInfoInventory();

            pmsSkuInfos.forEach(pmsSkuInfo -> {

//                HashMap<String, Object> map = new HashMap<>();
//                map.put(pmsSkuInfo.getSkuId().toString(), pmsSkuInfo.getInventory());

//                redisService.expire("sku:inventory", randomTime, TimeUnit.SECONDS);

//                redisService.setCacheMap("sku:inventory", map);

                redisService.setCacheObject("inventory:" + pmsSkuInfo.getSkuId(),
                        pmsSkuInfo.getInventory());
            });
        } finally {
            // 释放锁
            redisService.deleteObject(LOCK_KEY);
        }

//        Object cacheObject = redisService.getCacheObject("inventory:1");
//        Map<String, Object> cacheMap = redisService.getCacheMap("sku:inventory");
//        cacheMap.forEach((k, v) -> {
//            if (k.equals("1")){
//                System.out.println(v);
//            }
//        });
//        System.out.println("---------------------------------------------------------------");
//        System.out.println(cacheObject);

    }
}
